package com.tim.app.ui.activity.selected;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.ClickUtil;
import com.application.library.util.KeyboardChangeListener;
import com.application.library.util.StringUtil;
import com.application.library.widget.ScrollGridView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.manager.ImagePickerManager;
import com.tim.app.server.api.API_App;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.server.entry.DynamicItem;
import com.tim.app.server.entry.User;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.UploadResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.adapter.story.DynamicImageAdapter;
import com.tim.app.ui.dialog.TipDialog;
import com.tim.app.ui.widget.imagepick.bean.ImageItem;
import com.tim.app.ui.widget.imagepick.ui.ImagePreviewActivity;
import com.tim.app.ui.widget.imagepick.ui.ImagePreviewTopicActivity;
import com.tim.app.util.SoftKeyboardUtil;
import com.tim.app.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 发布动态
 */
public class PublishDynamicActivity extends BaseActivity implements KeyboardChangeListener.KeyBoardListener {

    private static final String TAG = "PublishDynamicActivity";

    private static final int MAX_PICTURE = Integer.MAX_VALUE;
    private TextView tvSend;
    private ImagePickerManager imagePicker;
    private EditText etContent;
    private boolean isCanFinish = false;
    private ScrollGridView gvPic;
    private TextView tvBack;
    private static final int MAX_IMAGE_NUMBER = 6;

    private List<DynamicItem> selectItem;
    private DynamicImageAdapter dynamicImageAdapter;
    DynamicItem addItem;

    private final int MAX_DES = 140;
    private final int MAX_DES_BYTE = MAX_DES;

    private TextView tvCurrentInputCount;

    private KeyboardChangeListener mKeyboardChangeListener;

    private View svInputContent;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_post_dynamic;
    }

    @Override
    public void initView() {
        tvSend = (TextView) findViewById(R.id.tvSend);
        etContent = (EditText) findViewById(R.id.etContent);
        gvPic = (ScrollGridView) findViewById(R.id.gvPic);
        tvBack = (TextView) findViewById(R.id.tvBack);
        tvCurrentInputCount = (TextView) findViewById(R.id.tvCurrentInputCount);

        svInputContent = findViewById(R.id.svInputContent);
        tvBack.setOnClickListener(this);

        tvSend.setOnClickListener(this);
        imagePicker = ImagePickerManager.ins();
        imagePicker.setMultiMode(true);
        imagePicker.setSelectLimit(MAX_PICTURE);
        selectItem = new ArrayList<>();
        imagePicker.setCrop(true);
        if (android.os.Build.MODEL.contains("HM NOTE")) {
            imagePicker.setShowCamera(false);
        }
        dynamicImageAdapter = new DynamicImageAdapter(this);
        dynamicImageAdapter.setData(selectItem);
        gvPic.setAdapter(dynamicImageAdapter);
        gvPic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                if (selectItem.get(position).getType() == DynamicItem.TYPE_ADD) {
                    if (selectItem.size() < MAX_IMAGE_NUMBER) {
                        imagePicker.setSelectLimit(MAX_IMAGE_NUMBER - selectItem.size() + 1);
                    } else {
                        imagePicker.setSelectLimit(MAX_IMAGE_NUMBER - selectItem.size());
                    }
                    imagePicker.gallerySelectedPic(PublishDynamicActivity.this);
                } else {
                    ArrayList<ImageItem> images = new ArrayList<>();
                    for (int i = 0; i < selectItem.size(); i++) {
                        DynamicItem data = selectItem.get(i);
                        if (DynamicItem.TYPE_ADD != data.getType()) {
                            ImageItem imageItem = new ImageItem();
                            imageItem.path = data.getPath();
                            imageItem.isFromNet = false;
                            images.add(imageItem);
                        }
                    }
                    Intent intent = new Intent(PublishDynamicActivity.this, ImagePreviewTopicActivity.class);
                    intent.putExtra(ImagePickerManager.EXTRA_SELECTED_IMAGE_POSITION, position);
                    intent.putExtra(ImagePickerManager.EXTRA_IMAGE_ITEMS, images);
                    intent.putExtra(ImagePreviewActivity.ISORIGIN, false);
                    PublishDynamicActivity.this.startActivity(intent);  //如果是多选，点击图片进入预览界面
                }
            }
        });
        addItem = new DynamicItem();
        addItem.setType(DynamicItem.TYPE_ADD);
        mKeyboardChangeListener = new KeyboardChangeListener(this);
        mKeyboardChangeListener.setKeyBoardListener(this);
        EventManager.ins().registListener(EventTag.ON_AT, eventListener);
        EventManager.ins().registListener(EventTag.DELETE_DYNAMIC_IMAGE, eventListener);

        tvCurrentInputCount.setText(getString(R.string.inputCount, "0"));
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (s.length() <= MAX_DES_BYTE) {
                    currentDes = etContent.getText().toString().trim();
                }
                if (!StringUtil.checkEmojText(etContent.getText().toString().trim())) {
                    indexDes = etContent.getSelectionStart();
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                showOrHideSendView();
                String dexChange = etContent.getText().toString().trim();
                if (dexChange.contains("...")) {
                    return;
                }
                if (StringUtil.checkEmojText(dexChange)) {
                    ToastUtil.showToast(RT.getString(R.string.disable_emoji));
                    etContent.setText(StringUtil.replaceEmojText(dexChange));
                    etContent.setSelection(indexDes);
                    return;
                }
                tvCurrentInputCount.setText(getString(R.string.inputCount, String.valueOf(etContent.getText().toString().length())));
                if (intro.length() > MAX_DES) {
                    intro = etContent.getText().toString().trim();
                    if (intro.length() > MAX_DES) {
                        ToastUtil.showToast("内容不能超过140个字");
                    }
                } else {
                    intro = etContent.getText().toString().trim();
                    if (intro.length() > MAX_DES) {
                        etContent.setText(currentDes);
                        etContent.setSelection(currentDes.length());
                        ToastUtil.showToast("内容不能超过140个字");
                    }
                }
            }

        });
        svInputContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                SoftKeyboardUtil.hideSoftKeyboard(etContent);
                return false;
            }
        });
    }

    private String intro = "";
    private String currentDes = "";
    private int indexDes;

    private void showOrHideSendView() {
        if (selectItem.size() == 1 && TextUtils.isEmpty(etContent.getText().toString())) {
            tvSend.setEnabled(false);
        } else {
            tvSend.setEnabled(true);
        }
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ON_AT:
                    User user = (User) dataobj;
                    if (null != user && !TextUtils.isEmpty(user.getName())) {
                        //TODO @
                    }
                    break;
                case EventTag.DELETE_DYNAMIC_IMAGE:
                    int position = (int) dataobj;
                    if (selectItem.size() == MAX_IMAGE_NUMBER) {
                        selectItem.remove(position);
                        if (selectItem.get(selectItem.size() - 1).getType() != DynamicItem.TYPE_ADD) {
                            selectItem.add(addItem);
                        }
                    } else {
                        selectItem.remove(position);
                    }
                    dynamicImageAdapter.notifyDataSetChanged();
                    showOrHideSendView();
                    break;
            }

        }
    };

    @Override
    public void initData() {
        selectItem.add(addItem);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
        SoftKeyboardUtil.hideSoftKeyboard(etContent);
        EventManager.ins().removeListener(EventTag.ON_AT, eventListener);
        EventManager.ins().removeListener(EventTag.DELETE_DYNAMIC_IMAGE, eventListener);
    }


    @Override
    public void onBackPressed() {
        SoftKeyboardUtil.hideSoftKeyboard(etContent);
        if (isCanFinish) {
            super.onBackPressed();
        } else {
            String content = etContent.getText().toString();
            if (TextUtils.isEmpty(content)) {
                isCanFinish = true;
                finish();
                return;
            }
            showExitDialog();
        }
    }

    boolean isKeyboardShow = false;

    @Override
    public void onKeyboardChange(boolean isShow, int keyboardHeight) {
        isKeyboardShow = isShow;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibKeyboard:
                if (isKeyboardShow) {
                    SoftKeyboardUtil.hideSoftKeyboard(etContent);
                } else {
                    SoftKeyboardUtil.showSoftKeyboard(etContent);
                }
                break;
            case R.id.ibAt:
                Intent intent = new Intent(PublishDynamicActivity.this, AtSomeOneActivity.class);
                startActivity(intent);
                break;
            case R.id.ib_picture:
                SoftKeyboardUtil.hideSoftKeyboard(etContent);

                break;
            case R.id.tvSend:// 发布动态
                if (ClickUtil.isFastDoubleClick()) return;
                SoftKeyboardUtil.hideSoftKeyboard(etContent);
                String content = etContent.getText().toString();
                int imageSize = 0;
                if (selectItem.get(selectItem.size() - 1).getType() == DynamicItem.TYPE_ADD) {
                    imageSize = selectItem.size() - 1;
                } else {
                    imageSize = selectItem.size();
                }
                post(content, imageSize, 0);
                break;
            case R.id.tvBack:
                onBackPressed();
                break;
        }
    }

    boolean isCanSend = true;//允许发送

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePickerManager.RESULT_CODE_ITEMS) {
            if (data == null) {
                return;
            }
            if (requestCode == ImagePickerManager.RESULT_CODE_GALLERY) {//从图库返回
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePickerManager.EXTRA_RESULT_ITEMS);
                selectItem.remove(addItem);
                for (int i = 0; i < images.size(); i++) {
                    ImageItem item = images.get(i);
                    DynamicItem dynamicItem = new DynamicItem();
                    dynamicItem.setPath(item.path);
                    selectItem.add(dynamicItem);
                }
                if (selectItem.size() < MAX_IMAGE_NUMBER) {
                    selectItem.add(addItem);
                }
                dynamicImageAdapter.notifyDataSetChanged();
                showOrHideSendView();
            }
        } else if (requestCode == ImagePickerManager.REQUEST_CODE_TAKE) {
            //发送广播通知图片增加了
            ImagePickerManager.galleryAddPic(this, imagePicker.getTakeImageFile());
            ImageItem imageItem = new ImageItem();
            imageItem.path = imagePicker.getTakeImageFile().getAbsolutePath();
            imagePicker.clearSelectedImages();
            imagePicker.addSelectedImageItem(0, imageItem, true);
            selectItem.remove(addItem);
            DynamicItem dynamicItem = new DynamicItem();
            dynamicItem.setPath(imagePicker.getTakeImageFile().getAbsolutePath());
            selectItem.add(dynamicItem);
            if (selectItem.size() < MAX_IMAGE_NUMBER) {
                selectItem.add(addItem);
            }
            dynamicImageAdapter.notifyDataSetChanged();
            showOrHideSendView();
        } else if (resultCode == RESULT_OK) {
            if (requestCode == AppKey.REQUEST_CODE_PROBLEM_CONTENT) {
                setResult(RESULT_OK);
                finish();
            }
        }
    }

    String images = "";
    private int index;

    private void post(final String content, final int imageSize, final int position) {
        tvSend.setEnabled(false);
        if (imageSize == 0) {
            postDynamic(content, "");
        } else {
            if (position == 0) {
                images = "";
            }
            index = position;
            if (index < imageSize) {
                if (selectItem.get(index).getType() != DynamicItem.TYPE_ADD) {
                    showLoadingDialog();
                    API_App.ins().uploadData(TAG, selectItem.get(index).getPath(), new StringResponseCallback() {
                        @Override
                        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                            hideLoadingDialog();
                            index++;
                            if (errCode == ResponseResult.ResultStatus.OK) {
                                UploadResult result = new Gson().fromJson(resultValue, UploadResult.class);
                                if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                                    String url = result.getRes().getHashmap().getImgurl();
                                    images += url + AppKey.SEPARATOR;

                                    if (index == imageSize) {
                                        if (!TextUtils.isEmpty(images)) {
                                            images = images.substring(0, images.length() - 1);
                                        }
                                        if (isCanSend) {
                                            isCanSend = false;
                                            postDynamic(content, images);
                                        }
                                    } else {
                                        post(content, imageSize, index);
                                    }
                                }
                            } else {
                                if (index == imageSize) {
                                    if (!TextUtils.isEmpty(images)) {
                                        images = images.substring(0, images.length() - 1);
                                    }
                                    if (isCanSend) {
                                        isCanSend = false;
                                        postDynamic(content, images);
                                    }
                                }
                            }
                            return false;
                        }
                    });
                }
            }
        }
    }

    /**
     * 发表动态
     *
     * @param content
     * @param images
     */
    private void postDynamic(String content, String images) {
        if (TextUtils.isEmpty(content) && TextUtils.isEmpty(images)) {
            ToastUtil.showToast("回答不能为空！");
            return;
        }
        showLoadingDialog();
        API_Found.ins().postDynamic(TAG, content, content, images, AppKey.TYPE_DYNAMIC, "", "", new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                isCanSend = true;
                hideLoadingDialog();
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    tvSend.setEnabled(true);
                    EventManager.ins().sendEvent(EventTag.ON_DYNAMIC_ADD, 0, 0, null);
                    API_Statistics.ins().addActionData(TAG, PublishDynamicActivity.this, "say");
                    ToastUtil.showToast("发送成功！");
                    finish();
                } else {
                    tvSend.setEnabled(true);
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    private void showExitDialog() {
        TipDialog dialog = new TipDialog(this);
        dialog.setTextDes(getString(R.string.cancel_exit_dialog_content));
        dialog.setButton1(getString(R.string.action_ok), new TipDialog.DialogButtonOnClickListener() {
            @Override
            public void onClick(View button, TipDialog dialog) {
                dialog.dismiss();
                isCanFinish = true;
                finish();
            }
        });
        dialog.setButton2(getString(R.string.action_cancel), new TipDialog.DialogButtonOnClickListener() {
            @Override
            public void onClick(View button, TipDialog dialog) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

}
